<?php

namespace App\Http\Controllers\Backend\AppUpdate;

use App\Constants\RedisKey;
use App\Http\Requests\Backend\AppUpdate\AppUpdateRequest;
use App\Models\AppUpdateInfo;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Redis;

class AppUpdateController extends Controller {
    public function __construct() {
        $this->middleware('auth:backend');
        $this->user = auth('backend')->user();
    }
    //
    public function changeConnection(){
        $model = new AppUpdateInfo();
        $model->setConnection('backend');
        return $model;
    }

    /**
     * 首页
     * @param AppUpdateRequest $request
     * @return mixed
     * @author luwei
     * @date 2019-01-09 11:59
     */
    public function index(AppUpdateRequest $request) {
        $model = $this->changeConnection();
        $appInfo = $model->cursor();
        $info    = [];
        foreach ($appInfo as $v) {
            $info[] = [
                'id'              => $v->id,
                'app_update_time' => $v->app_update_time->format('Y-m-d H:i:s'),
                'title'           => $v->title,
                'version'         => $v->version,
                'install_pkg_url' => $v->install_pkg_url,
                'ios_pkg_url'     => $v->ios_pkg_url,
                'app_update_text' => $v->app_update_text,
                'status'          => $v->status,
                'status_str'      => $v->status_str,
                'is_force'        => $v->is_force
            ];
        }
        return success($info);
    }

    /**
     * 新增更新日志
     * @param AppUpdateRequest $request
     * @author luwei
     * @date 2019-01-09 11:49
     * @return
     */
    public function store(AppUpdateRequest $request) {
        $params           = $this->extractInputFromRules($request, $request->rules());
        $params['status'] = AppUpdateInfo::STATUS_USE;
        $appInfo          = AppUpdateInfo::where(['status' => AppUpdateInfo::STATUS_USE])->first();
        if ($appInfo) {
            $appInfo->update(['status' => AppUpdateInfo::STATUS_NOT_USE]);
        }
        AppUpdateInfo::create($params);
        $key = RedisKey::APP_UPDATE_INFO;
        //清除已经有的app版本信息缓存
        Redis::del($key);
        return success([]);
    }
}
